import React from 'react';
import { message, Modal } from 'antd';
import { WeaErrorPage, WeaTools, WeaRightMenu } from 'ecCom';
const { ls } = WeaTools;
import Immutable from 'immutable';
const { is, fromJS } = Immutable;
//引入元素组件
import LayoutFlags from './LayoutFlags';
import objectAssign from 'object-assign';
import { handlePortalSynize, onShowOrHideAllE, openFavouriteBrowser, showHelp } from '../util/rcmenu';
//门户组件
class Homepage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hpdata: null,
            params: {},
        }
        this.handleParams = this.handleParams.bind(this);
        this.getPortalData = this.getPortalData.bind(this);
        this.getRightMenu = this.getRightMenu.bind(this);
        this.onRightMenuClick = this.onRightMenuClick.bind(this);
        this.handleAddElement = this.handleAddElement.bind(this);
        this.handleRefresh = this.handleRefresh.bind(this);
    }
    handleParams(props){
        let query = {};
        if(props.location) query = props.location.query
        let params = objectAssign({},props.params,query);
        if(props.hpid) {
            if(props.formData && typeof props.formData === 'object') props.formData = JSON.stringify(props.formData);
            params = objectAssign(params, props);
            if(!params.isSetting) params.isSetting = false;
        }else{
            params.isSetting = false;
            params.isfromportal = 1;
            params.isfromhp = 0;
        }

        return params;
    }
    getPortalData(params){
        const { hpid, isSetting } = params;
        let cacheData = ls.getJSONObj('portal-'+hpid+'-'+isSetting);
        if(cacheData){
            this.setState({
                hpdata: cacheData,
                params,
            });
/*            if(isSetting){
                $("#e9PortalSetting").css({background:cacheData.hpinfo.bgcolor});
            }else{
                $("#e9routeMain").css({background:cacheData.hpinfo.bgcolor});
            }*/
        }
        WeaTools.callApi('/api/portal/homepage/hpdata', 'POST', params).then( data => {
            if(data.status === 'failed'){
                message.error(data.errormsg);
            }else{
                ls.set('portal-'+hpid+'-'+isSetting, data);
                window.isPortalRender = false;
                this.setState({
                    hpdata: data,
                    params: params,
                });
      /*          if(isSetting){
                    $("#e9PortalSetting").css({background:cacheData.hpinfo.bgcolor});
                }else{
                    $("#e9routeMain").css({background:cacheData.hpinfo.bgcolor});
                }*/
            }
        });
    }
    handleRefresh(nParams){
        const params = this.handleParams(this.props);
        this.getPortalData({...params,...nParams});
    }
    handleAddElement(element, areaflag, index){
        const { hpid, isSetting } = this.state.params;
        //获取当前设置门户信息
        let hpdata = fromJS(this.state.hpdata).toJSON();
        const layoutFlags = hpdata.hpinfo.layoutFlags;
        for (var i = 0; i < layoutFlags.length; i++) {
            let layoutFlag = layoutFlags[i];
            if(layoutFlag.areaflag === areaflag){
                let areaElements = layoutFlag.areaElements;
                areaElements.splice(index, 0, element.config);
                break;
            }
        }
        hpdata.hpCss += element.eCss;
        ls.set('portal-'+hpid+'-'+isSetting, hpdata);
        this.setState({
            hpdata,
        });
    }
    componentWillMount(){
        const params = this.handleParams(this.props);
        this.getPortalData(params);
    }
    componentDidMount(){
        const params = this.handleParams(this.props);
        if(this.refs.btnWfCenterReload) this.refs.btnWfCenterReload.setAttribute("onclick","elmentReLoad()");
    }
    shouldComponentUpdate(nextProps, nextState){
        return window.isPortalRender || !is(fromJS(this.state),fromJS(nextState)) || !is(fromJS(this.props),fromJS(nextProps));
    }
    componentWillReceiveProps(nextProps) {
        const params = this.handleParams(this.props);
        const nParams = this.handleParams(nextProps);
        if(!is(fromJS(params),fromJS(nParams)) || window.isPortalRender){
            this.getPortalData(nParams);
        }
    }
    componentWillUnmount() {
       // $("#e9routeMain").css({background:''});
    }
    render() {
        const { params, hpdata } = this.state;
        if(params.hpid){
            let hpHtml = <div/>;
            let styleStr = "";
            const { hpid, subCompanyId, isSetting } = params;
            let layoutid = '';
            if(hpdata){
                if(hpdata.hasRight){
                    layoutid = hpdata.hpinfo.bLayoutid;
                    const layoutObj = {
                         config: {
                            isRender: window.isPortalRender,
                            isremembertab: hpdata.hpinfo.isremembertab,
                            isSetting: hpdata.hpinfo.isSetting,
                         },
                         layoutFlags: hpdata.hpinfo.layoutFlags,
                         layoutid: hpdata.hpinfo.bLayoutid,
                         layoutHtml: hpdata.hpinfo.html
                    };
                    let coord = isSetting ? 'td[coord] { border: 1px dashed #EA8237; border-top: none; }' : '';
                    styleStr = "<style type='text/css'>" + coord + hpdata.hpCss.replace(/\"/g, "") + "</style>";
                    hpHtml = <LayoutFlags {...layoutObj}/>
                }else{
                    hpHtml = <NoRightPage msg={hpdata.msg}/>;
                }
            }
            return <div className='homepage'
                        data-hpid={hpid} 
                        data-subcompanyid={subCompanyId} 
                        data-issetting={isSetting} 
                        data-layoutid={layoutid}>
                        <div dangerouslySetInnerHTML = {{__html:styleStr}}></div>
                        <input type="hidden" ref="btnWfCenterReload" value="btnWfCenterReload" id="btnWfCenterReload" name="btnWfCenterReload"/>
                        <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick}>
                            {hpHtml}
                        </WeaRightMenu>
                 </div>
        } else {
            return <div className='homepage'></div>;
        }
    }
    getRightMenu(){
        let btns = [];
        const { hpdata } = this.state;
        if(hpdata){
            hpdata.rcmenu.map(menu=>{
                btns.push({
                    key: menu.key,
                    icon: <i className={menu.icon}/>,
                    content: menu.label,
                }); 
            });
        }
        return btns
    }
    onRightMenuClick(key){
        const { params } = this.state;
        let _params = {...params};
        _params.isSetting = true;
        _params.opt = 'edit';
        switch(key){
            case 'synihp':
            case 'synihpnormal':
                handlePortalSynize({
                    hpid: _params.hpid,
                    subCompanyId: _params.subCompanyId,
                    method: key
                });
                break;
            case 'shrinkAll':
                onShowOrHideAllE(params.isSetting);
                break;
            case 'settingElement':
                window.handlePortalSetting(_params);    
                break;
            case 'store':
                openFavouriteBrowser();
                break;
            case 'help':
                showHelp();
                break;
            case '5':
                break;
        }
    }
}
 //无权限门户
 const NoRightPage = ({ msg }) =>
     <div className = "page-noright">
         <img src = "/images/ecology8/noright_wev8.png" width = "162px" height = "162px" />
         <div style = {{ color: 'rgb(255,187,14)' } }>{msg}</div>
     </div>

class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
            return ( <WeaErrorPage msg = { hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" }/>
        );
    }
}

Homepage = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(Homepage);
export default Homepage;
